package com.lcb.jmm.volatiledome;

/****
 * @Author:lcb
 * @Description:线程可见性
 * @Date: 2020-12-23 11:31
 *****/
public class VolatileVisibilitySample {
    // volatile private boolean initFlag = false;
    private boolean initFlag = false;
    static Object object = new Object();

    public void refresh() {
        this.initFlag = true; //普通写 (volatile)
        String name = Thread.currentThread().getName();
        System.out.println(String.format("线程:%s:修改共享变量initFlag", name));
    }

    public void load() {
        String name = Thread.currentThread().getName();
        int i = 0;
        while (!initFlag) {
                i++;
        }
        System.out.println("线程：" + name + "当前线程嗅探到initFlag的状态的改变");
    }

    public static void main(String[] args) {

        final VolatileVisibilitySample sample = new VolatileVisibilitySample();

        Thread threadA = new Thread(new Runnable() {
            public void run() {
                sample.refresh();
            }
        }, "threadA");

        Thread threadB = new Thread(new Runnable() {
            public void run() {
                sample.load();
            }
        }, "threadB");

        threadB.start();

        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        threadA.start();
    }
}
